<template>
  <s-layout title="确认订单">
    <view class="bg-white address-box ss-m-b-14 ss-r-b-10" @tap="onSelectAddress">
      <s-address-item :item="state.addressInfo" :hasBorderBottom="false">
        <view class="ss-rest-button"><text class="_icon-forward"></text></view>
      </s-address-item>
    </view>
    <view class="order-card-box ss-m-b-14">
      <s-goods-item
        v-for="item in info.orderDetailList"
        :key="item.productId"
        :img="item.image"
        :title="item.productName"
        :skuText="item.sku"
        :price="item.price"
        :num="item.payNum"
        marginBottom="10"
      >
        <template #top>
          <view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white">
            <view class="item-title">配送方式</view>
            <view class="ss-flex ss-col-center">
              <text class="item-value">普通快递</text>
            </view>
          </view>
        </template>
      </s-goods-item>

      <view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-10">
        <view class="item-title">订单备注</view>
        <view class="ss-flex ss-col-center">
          <uni-easyinput
            maxlength="20"
            placeholder="建议留言前先与商家沟通"
            v-model="state.mark"
            :inputBorder="false"
            :clearable="false"
          ></uni-easyinput>
        </view>
      </view>
      <view class="ss-p-x-20 bg-white ss-r-10">
        <view class="item-title">
          <view>支付方式</view>
          <view class="list">
            <view
              class="flex middle pay-item"
              :class="state.active == index ? 'on' : ''"
              @click="payItem(index)"
              v-for="(item, index) in cartArr"
              :key="index"
            >
              <view class="name flex cell-main">
                <view class="iconfont animated" :class="item.icon"> </view>
                {{ item.name }}
              </view>
              <view class="tip">{{ item.title }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 合计 -->
    <view class="bg-white total-card-box ss-p-20 ss-m-b-14 ss-r-10">
      <view class="total-box-content border-bottom">
        <view class="order-item ss-flex ss-col-center ss-row-between">
          <view class="item-title">商品金额</view>
          <view class="ss-flex ss-col-center">
            <text class="item-value ss-m-r-24">￥{{ info.proTotalFee }}</text>
          </view>
        </view>
        <view
          class="order-item ss-flex ss-col-center ss-row-between"
          v-if="state.orderPayload.order_type === 'score'"
        >
          <view
            class="item acea-row row-between-wrapper"
            v-if="
              !info.bargainId && !info.combinationId && !info.seckillId && productType === 'normal'
            "
          >
            <view>积分抵扣</view>
            <!-- 	 -->
            <view class="discount acea-row row-middle">
              <view>
                {{ useIntegral ? '剩余积分' : '当前积分' }}
                <text class="num font-color">{{
                  useIntegral ? info.surplusIntegral : info.userIntegral || 0
                }}</text>
              </view>
              <checkbox-group @change="ChangeIntegral">
                <checkbox
                  :checked="useIntegral ? true : false"
                  :disabled="info.userIntegral == 0 && !useIntegral"
                />
              </checkbox-group>
            </view>
          </view>
        </view>
        <view class="order-item ss-flex ss-col-center ss-row-between">
          <view class="item-title">运费</view>
          <view class="ss-flex ss-col-center">
            <view class="discount" v-if="parseFloat(orderInfoVo.freightFee) > 0">
              +￥{{ orderInfoVo.freightFee }}
            </view>
            <view class="discount" v-else>免运费</view>
          </view>
        </view>
        <view
          class="order-item ss-flex ss-col-center ss-row-between"
          v-if="state.orderPayload.order_type != 'score'"
        >
          <!-- <view v-if="state.orderInfo.coupon_discount_fee > 0" class="order-item ss-flex ss-col-center ss-row-between"> -->
          <view class="item-title">优惠券</view>
          <view class="ss-flex ss-col-center" @tap="state.showCoupon = true">
            <text class="item-value text-red" v-if="state.couponId"
              >-￥{{ state.couponTitle }}</text
            >

            <text class="_icon-forward item-icon"></text>
          </view>
        </view>
        <view
          class="order-item ss-flex ss-col-center ss-row-between"
          v-if="state.orderInfo.promo_infos?.length"
        >
          <!-- <view v-if="state.orderInfo.promo_discount_fee > 0" class="order-item ss-flex ss-col-center ss-row-between"> -->
        </view>
      </view>
      <view class="total-box-footer ss-font-28 ss-flex ss-row-right ss-col-center ss-m-r-28">
        <view class="total-num ss-m-r-20">共{{ state.totalNumber }}件</view>
        <view>合计：</view>
        <view class="total-num text-red"> ￥{{ info.payFee }} </view>
      </view>
    </view>
    <!-- 选择优惠券弹框 -->
    <s-coupon-select
      v-model="state.couponInfo"
      :show="state.showCoupon"
      @confirm="onSelectCoupon"
      @close="state.showCoupon = false"
    />
    <!-- 满额折扣弹框  -->
    <s-discount-list
      v-model="state.orderInfo"
      :show="state.showDiscount"
      @close="state.showDiscount = false"
    />
    <!-- 底部 -->
    <su-fixed bottom :opacity="false" bg="bg-white" placeholder :noFixed="false" :index="200">
      <view class="footer-box border-top ss-flex ss-row-between ss-p-x-20 ss-col-center">
        <view class="total-box-footer ss-flex ss-col-center">
          <view class="total-num ss-font-30 text-red"> ￥{{ info.payFee }} </view>
          <view v-if="state.orderPayload.order_type === 'score'" class="ss-flex">
            <view class="total-num ss-font-30 text-red ss-m-l-4">+</view>
            <image
              :src="mall.$url.static('/static/img/shop/goods/score1.svg')"
              class="score-img"
            ></image>
            <view class="total-num ss-font-30 text-red">{{ state.orderInfo.score_amount }}</view>
          </view>
        </view>

        <button
          class="ss-reset-button ui-BG-Main-Gradient ss-r-40 submit-btn ui-Shadow-Main"
          @tap="onConfirm"
        >
          {{ exchangeNow ? '立即兑换' : '提交订单' }}
        </button>
      </view>
    </su-fixed>
  </s-layout>
</template>

<script setup>
import { reactive, computed } from 'vue';
import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app';
import mall from '@/mall';
import { isEmpty } from 'lodash';
import {
  //orderConfirm,
  getCouponsOrderPrice,
  orderCreate,
  postOrderComputed,
  wechatOrderPay,
  wechatQueryPayResult,
  loadPreOrderApi,
} from '@/mall/api/orderApi.js';
import { getAddressDefault } from '@/mall/api/user';

const state = reactive({
  orderPayload: {},
  orderInfo: {},
  addressInfo: {},
  invoiceInfo: {},
  totalNumber: 0,
  showCoupon: false,
  couponInfo: [],
  showDiscount: false,
  active: '',
  payType: '',
  couponId: '',
  preOrderNo: '',
  mark: '',
});
const info = ref({});
const cartArr = ref([
  {
    name: '微信支付',
    icon: 'icon-weixin2',
    value: 'weixin',
    title: '微信快捷支付',
    payStatus: 1,
  },
  {
    name: '余额支付',
    icon: 'icon-icon-test',
    value: 'yue',
    title: '可用余额:',
    payStatus: 1,
  },
]);
// 立即兑换(立即兑换无需跳转收银台)
const exchangeNow = computed(
  () => state.orderPayload.order_type === 'score' && state.orderInfo.pay_fee == 0,
);

// 选择地址
function onSelectAddress() {
  uni.$once('SELECT_ADDRESS', (e) => {
    changeConsignee(e.addressInfo);
  });
  mall.$router.go('/pages/user/address/list');
}

// 更改收货人地址&计算订单信息
async function changeConsignee(addressInfo = {}) {
  if (isEmpty(addressInfo)) {
    const { error, data } = await getAddressDefault();
    addressInfo = data;
  }
  if (!isEmpty(addressInfo)) {
    state.addressInfo = addressInfo;
    state.orderPayload.address_id = state.addressInfo.id;
  }
}
function payItem(e) {
  state.active = e;

  state.payType = cartArr.value[e].value;
  computedPrice();
}
// 选择优惠券
async function onSelectCoupon(e) {
  state.orderPayload.coupon_id = e || 0;
  state.showCoupon = false;
}

// 选择发票信息
function onSelectInvoice() {
  uni.$once('SELECT_INVOICE', (e) => {
    state.invoiceInfo = e.invoiceInfo;
    state.orderPayload.invoice_id = e.invoiceInfo.id || 0;
  });
  mall.$router.go('/pages/user/invoice/list');
}

// 提交订单/立即兑换
function onConfirm() {
  if (!state.payType) return mall.$helper.toast('请选择支付方式');

  if (!state.addressInfo.id) return mall.$helper.toast('请选择收货地址');

  if (state.payType == 'yue' && info.value.userBalance < info.payFee) {
    return mall.$helper.toast('余额不足！');
  }
  uni.showLoading({
    title: '订单支付中',
  });
  payment({
    realName: '',
    phone: '',
    addressId: state.addressInfo.id,
    couponId: state.couponId,
    payType: state.payType,
    useIntegral: 0,
    preOrderNo: state.preOrderNo,
    mark: state.mark,
    storeId: state.storeId || 0,
    shippingType: 1,
    payChannel: 'public',
  });
}
function payment(data) {
  orderCreate(data)
    .then((res) => {
      onPay(res.data.orderNo);
      uni.hideLoading();
    })
    .catch((err) => {
      uni.hideLoading();
      return mall.$helper.toast(err);
    });
}

// 创建订单&跳转
async function topage() {
  const { error, data } = await mall.$api.order.create(state.orderPayload);
  if (error === 0) {
    // 更新购物车列表
    if (state.orderPayload.from === 'cart') {
      mall.$store('cart').getList();
    }
    if (exchangeNow.value) {
      mall.$router.redirect('/pages/pay/result', {
        orderSN: data.order_sn,
      });
    } else {
      mall.$router.redirect('/pages/pay/index', {
        orderSN: data.order_sn,
      });
    }
  }
}
const onPay = (orderNo) => {
  if (state.payType === 'yue') {
    uni.showModal({
      title: '提示',
      content: '确定要支付吗?',
      success: function (res) {
        if (res.confirm) {
          mall.$platform.pay(state.payType, 'goods', orderNo);
        }
      },
    });
  } else {
    mall.$platform.pay(state.payment, 'goods', orderNo);
  }
};
function getOrderPay(orderNo, message) {
  let url = '/pages/order_pay_status/index?order_id=' + orderNo + '&msg=' + message;
  wechatOrderPay({
    orderNo: orderNo,
    payChannel: 'public',
    payType: state.payType,
    scene: 0, //下单时小程序的场景值
  })
    .then((res) => {
      let jsConfig = res.data.jsConfig;
      switch (res.data.payType) {
        case 'weixin':
          // #ifdef MP
          uni.requestPayment({
            timeStamp: jsConfig.timeStamp,
            nonceStr: jsConfig.nonceStr,
            package: jsConfig.packages,
            signType: jsConfig.signType,
            paySign: jsConfig.paySign,
            ticket: null,
            success: function (ress) {
              uni.hideLoading();
              wechatQueryPayResult(orderNo)
                .then((res) => {
                  uni.hideLoading();
                  if (info.value.bargainId || info.value.combinationId || info.value.seckillId)
                    return topage(url);
                })
                .cache((err) => {
                  uni.hideLoading();
                  return mall.$helper.toast(err);
                });
            },
            fail: function (e) {
              uni.hideLoading();
              return mall.$helper.toast('取消支付');
            },
            complete: function (e) {
              uni.hideLoading();
              //关闭当前页面跳转至订单状态
              if (e.errMsg == 'requestPayment:cancel') return mall.$helper.toast('取消支付');
            },
          });
          // #endif
          // #ifdef H5
          let data = {
            timestamp: jsConfig.timeStamp,
            nonceStr: jsConfig.nonceStr,
            package: jsConfig.packages,
            signType: jsConfig.signType,
            paySign: jsConfig.paySign,
          };
          that.$wechat
            .pay(data)
            .then((res) => {
              if (res.errMsg == 'chooseWXPay:cancel') {
                uni.hideLoading();
                return that.$util.Tips(
                  {
                    title: '取消支付',
                  },
                  {
                    tab: 5,
                    url: goPages + '&status=2',
                  },
                );
              } else {
                wechatQueryPayResult(orderNo)
                  .then((res) => {
                    uni.hideLoading();
                    return that.$util.Tips(
                      {
                        title: '支付成功',
                        icon: 'success',
                      },
                      {
                        tab: 5,
                        url: goPages,
                      },
                    );
                  })
                  .cache((err) => {
                    uni.hideLoading();
                    return that.$util.Tips({
                      title: err,
                    });
                  });
              }
            })
            .cache((res) => {
              uni.hideLoading();
              return that.$util.Tips(
                {
                  title: '取消支付',
                },
                {
                  tab: 5,
                  url: goPages + '&status=0',
                },
              );
            });
          // #endif
          break;
        case 'yue':
          uni.hideLoading();
          return that.$util.Tips(
            {
              title: message,
            },
            {
              tab: 5,
              url: goPages + '&status=1',
            },
          );
          break;
        case 'weixinh5':
          uni.hideLoading();
          that.$util.Tips(
            {
              title: '订单创建成功',
            },
            {
              tab: 5,
              url: goPages + '&status=0',
            },
          );
          setTimeout(() => {
            location.href =
              jsConfig.mwebUrl +
              '&redirect_url=' +
              window.location.protocol +
              '//' +
              window.location.host +
              goPages +
              '&status=1';
          }, 100);
          break;
      }
    })
    .catch((err) => {
      uni.hideLoading();
      return that.$util.Tips({
        title: err,
      });
    });
}
// 计算订单价格
function computedPrice() {
  postOrderComputed({
    addressId: state.addressInfo.addressId,
    useIntegral: false,
    couponId: state.couponId,
    shippingType: 1,
    preOrderNo: state.preOrderNo,
  })
    .then((res) => {
      let data = res.data;
      info.value.couponFee = data.couponFee;
      //赋值操作，userIntegral 当前积分，surplusIntegral 剩余积分
      info.value.userIntegral = data.surplusIntegral;
      info.value.deductionPrice = data.deductionPrice;
      info.value.freightFee = data.freightFee;
      info.value.payFee = data.payFee;
      info.value.proTotalFee = data.proTotalFee;
      info.value.useIntegral = data.useIntegral;
      info.value.usedIntegral = data.usedIntegral;
      info.value.surplusIntegral = data.surplusIntegral;
      //info.value.userIntegral = data.userIntegral;
    })
    .catch((err) => {
      return mall.$helper.toast(err);
    });
}
async function queryInfo() {
  let { data } = await loadPreOrderApi(state.preOrderNo);
  info.value = data.orderInfoVo;
  cartArr.value[1].title = '可用余额:' + data.orderInfoVo.userBalance;
  state.totalNumber = 0;
  data.orderInfoVo.orderDetailList.forEach((item) => {
    state.totalNumber += item.payNum;
  });
}
onLoad(async (options) => {
  if (options.preOrderNo) {
    state.preOrderNo = options.preOrderNo;
    queryInfo();
    changeConsignee();
  }
});
</script>

<style lang="scss" scoped>
  :deep() {
    .uni-input-wrapper {
      width: 320rpx;
    }

    .uni-easyinput__content-input {
      font-size: 28rpx;
      height: 72rpx;
      text-align: right !important;
      padding-right: 0 !important;

      .uni-input-input {
        font-weight: 500;
        color: #333333;
        font-size: 26rpx;
        height: 32rpx;
        margin-top: 4rpx;
      }
    }
    .uni-easyinput__content {
      display: flex !important;
      align-items: center !important;
      justify-content: right !important;
    }
  }
  .score-img {
    width: 36rpx;
    height: 36rpx;
    margin: 0 4rpx;
  }
  .order-item {
    height: 80rpx;

    .item-title {
      font-size: 28rpx;
      font-weight: 400;
    }

    .item-value {
      font-size: 28rpx;
      font-weight: 500;
      font-family: OPPOSANS;
    }
    .text-disabled {
      color: #bbbbbb;
    }

    .item-icon {
      color: $dark-9;
    }

    .remark-input {
      text-align: right;
    }

    .item-placeholder {
      color: $dark-9;
      font-size: 26rpx;
      text-align: right;
    }
  }

  .total-box-footer {
    height: 90rpx;

    .total-num {
      color: #333333;
      font-family: OPPOSANS;
    }
  }

  .footer-box {
    height: 100rpx;

    .submit-btn {
      width: 240rpx;
      height: 70rpx;
      font-size: 28rpx;
      font-weight: 500;

      .goto-pay-text {
        line-height: 28rpx;
      }
    }

    .cancel-btn {
      width: 240rpx;
      height: 80rpx;
      font-size: 26rpx;
      background-color: #e5e5e5;
      color: $dark-9;
    }
  }
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }
  .subtitle {
    font-size: 28rpx;
    color: #999999;
  }
  .cicon-checkbox {
    font-size: 36rpx;
    color: var(--ui-BG-Main);
  }
  .cicon-box {
    font-size: 36rpx;
    color: #999999;
  }
  .pay-item {
    padding: 10px 0;
  }
</style>
